package com.intelligentmeterreadingsys.waterlist.copywater.activity;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.povo.ResourcesPoVo;
import com.intelligentmeterreadingsys.util.BitmapUtil;
import com.intelligentmeterreadingsys.util.FileNameUtil;
import com.intelligentmeterreadingsys.waterlist.copywater.db.CopyWaterDao;

/**
 * 图片显示
 * 
 * @author king
 * 
 */
public class ImageSwitcherActivity extends Activity implements OnItemSelectedListener, ViewFactory {
    public static final int ITEM0 = Menu.FIRST;// 系统值
    private static final int REQUEST_CODE_TAKE_IMAGE = 1;
    private ImageSwitcher imgsw;

    private Gallery gallery;

    private List<ResourcesPoVo> mThumbIds = null;

    private Context mContext;

    private String otherid = null;
    private String status = null;

    public boolean b = false;

    public int poston;// 当前位置

    public String imagepath;

    public String classname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);

	requestWindowFeature(Window.FEATURE_NO_TITLE);
	setContentView(R.layout.image_switcher_activity);
	imgsw = (ImageSwitcher) findViewById(R.id.imgswch1);
	gallery = (Gallery) findViewById(R.id.gallery);

	Intent intent = getIntent();
	Bundle bundle = intent.getExtras();

	otherid = bundle.getString("otherid");

	status = bundle.getString("status");
	classname = bundle.getString("classname");
	CopyWaterDao dao = new CopyWaterDao(ImageSwitcherActivity.this);
	mThumbIds = dao.queryResour(otherid, status);
	dao.close();
	if (mThumbIds == null || mThumbIds.size() < 1) {

	    Photograph();
	}
	init();
    }

    @Override
    /**
     * ʵ�ֵ�ViewFactory�ӿ�
     */
    public View makeView() {
	ImageView i = new ImageView(this);
	i.setBackgroundColor(0xFF000000);
	i.setScaleType(ImageView.ScaleType.FIT_CENTER);
	i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	return i;

    }

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	if (b) {
	    imgsw.setImageResource(mThumbIds.get(0).getId());
	} else {

	    Uri uri = Uri.parse(mThumbIds.get(arg2).getPath());
	    imgsw.setImageURI(uri);
	}

	poston = arg2;

    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
	// TODO Auto-generated method stub

    }

    public class ImageAdapter extends BaseAdapter {
	public ImageAdapter(Context c) {
	    mContext = c;
	}

	@Override
	public int getCount() {

	    if (b) {

		return 1;
	    }
	    return mThumbIds.size();

	}

	@Override
	public Object getItem(int position) {

	    return position;
	}

	@Override
	public long getItemId(int position) {

	    return position;
	}

	@Override
	/**
	 * ���ImageView
	 */
	public View getView(int position, View convertView, ViewGroup parent) {

	    ImageView i = new ImageView(mContext);
	    if (b) {
		i.setImageResource(mThumbIds.get(0).getId());
	    } else {
		FileInputStream f;
		try {
		    f = new FileInputStream(mThumbIds.get(position).getPath());
		    FileDescriptor fd = f.getFD();

		    BitmapFactory.Options options = new BitmapFactory.Options();
		    options.inJustDecodeBounds = true;
		    BitmapFactory.decodeFileDescriptor(fd, null, options);

		    options.inSampleSize = BitmapUtil.computeSampleSize(options, 80, 128 * 128);

		    options.inJustDecodeBounds = false;
		    Bitmap bm = BitmapFactory.decodeStream(f, null, options);

		    // Bitmap firstBitmap =
		    // BitmapFactory.decodeFile(imagepath.get(position));
		    i.setImageBitmap(bm);
		} catch (FileNotFoundException e) {

		    e.printStackTrace();
		} catch (IOException e) {

		    e.printStackTrace();
		}

	    }
	    // i.setImageResource(mThumbIds[position]);//ͼƬԴ

	    i.setAdjustViewBounds(true);
	    i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));// ͼƬ��С
	    if (b)
		i.setBackgroundResource(R.drawable.contraband);// ͼƬ����
	    return i;
	}

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	menu.add(0, ITEM0, 0, "拍照");
	menu.add(0, ITEM0 + 1, 0, "删除");
	menu.findItem(ITEM0 + 1);

	return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
	if (item.getItemId() == ITEM0) {
	    Photograph();
	} else if (item.getItemId() == ITEM0 + 1) {
	    if (classname.equals("CopyWaterRFIDActivity") || classname.equals("CopyWaterNoRFIDActivity") || classname.equals("EquipementAddActivity")) {

		delect();
	    } else {
		Toast.makeText(this, "不能删除", 1000).show();
		return false;
	    }

	}
	return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	if (requestCode == REQUEST_CODE_TAKE_IMAGE) {

	    if (resultCode == RESULT_OK) {

		File f = new File(imagepath);
		if (f.exists()) {
		    CopyWaterDao dao = new CopyWaterDao(ImageSwitcherActivity.this);
		    dao.insertImage(otherid, imagepath, status);
		    mThumbIds = dao.queryResour(otherid, status);
		    dao.close();
		    b = false;
		    FileInputStream fis = null;
		    try {
			fis = new FileInputStream(imagepath);
			FileDescriptor fd = fis.getFD();
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFileDescriptor(fd, null, options);
			options.inSampleSize = 3;
			options.inJustDecodeBounds = false;
			Bitmap mbitmap = BitmapFactory.decodeStream(fis, null, options);
			Matrix matrix = new Matrix();
			matrix.setRotate(90);
			mbitmap = Bitmap.createBitmap(mbitmap, 0, 0, mbitmap.getWidth(), mbitmap.getHeight(), matrix, true);
			FileOutputStream out = new FileOutputStream(imagepath);
			mbitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
			out.flush();
			out.close();
		    } catch (FileNotFoundException e) {

			e.printStackTrace();
		    } catch (IOException e) {

			e.printStackTrace();
		    }
		}

		init();
	    }

	} else if (resultCode == RESULT_CANCELED) {
	    mThumbIds = new ArrayList<ResourcesPoVo>();
	    ResourcesPoVo resour = new ResourcesPoVo();
	    resour.setId(R.drawable.contraband);
	    mThumbIds.add(resour);
	    b = true;
	    init();
	}

	super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onRestart() {
	System.out.println("onRestart");

	super.onRestart();
    }

    /**
     * 初始化
     */
    public void init() {
	imgsw.removeAllViews();
	imgsw.setFactory(this);
	imgsw.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
	imgsw.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
	gallery.setAdapter(new ImageAdapter(this));
	gallery.setOnItemSelectedListener(this);
    }

    /**
     * 删除一张照片
     */
    public void delect() {
	if (b) {
	    Toast.makeText(this, "没有图片不能进行此抄作", Toast.LENGTH_LONG).show();
	    return;
	}
	CopyWaterDao dao = new CopyWaterDao(this);
	boolean bb = dao.delectOne(mThumbIds.get(poston).getId() + "");
	File file = new File(mThumbIds.get(poston).getPath());
	file.delete();
	mThumbIds = dao.queryResour(otherid, status);
	dao.close();
	if (mThumbIds == null | mThumbIds.size() < 1) {
	    mThumbIds = new ArrayList<ResourcesPoVo>();
	    ResourcesPoVo resour = new ResourcesPoVo();
	    resour.setId(R.drawable.contraband);
	    mThumbIds.add(resour);
	    b = true;

	}
	init();
	if (bb) {
	    Toast.makeText(this, "删除成功", Toast.LENGTH_LONG).show();
	} else {
	    Toast.makeText(this, "删除失败", Toast.LENGTH_LONG).show();
	}
    }

    // 拍照
    public void Photograph() {

	if (otherid == null | otherid.trim().equals("")) {
	    Toast.makeText(ImageSwitcherActivity.this, "没有水表不能使用此功能", Toast.LENGTH_LONG).show();
	    return;
	}

	Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	FileNameUtil f = new FileNameUtil(this);
	imagepath = f.Orderimgpath();
	if (status.equals("2")) {
	    imagepath = f.Waterimgpath();
	} else if (status.equals("3")) {
	    imagepath = f.Reviewimgpath();
	} else if (status.equals("4")) {
	    imagepath = f.Equipement();
	} else if (status.equals("5")) {
	    imagepath = f.CheckEquipement();
	}

	if (imagepath == null) {
	    Toast.makeText(this, "SD卡不可用", Toast.LENGTH_LONG).show();
	    return;
	}
	String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";
	imagepath = imagepath + "/" + fileName;
	intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imagepath)));
	startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);
    }
}
